package com.hefan.api.controller.pay;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.util.CollectionUtils;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.api.service.pay.PayNotifyOprateLocalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by lxw on 2016/10/12.
 */
@Controller
@RequestMapping("/payNotify")
public class PayNotifyController {

    private Logger logger = LoggerFactory.getLogger(PayNotifyController.class);

    @Resource
    private PayNotifyOprateLocalService payNotifyOprateLocalService;

    /**
     * 微信支付回调通知
     * @param request
     * @param response
     */
    @RequestMapping("/wechatNotify")
    public void wechatPayNotify(HttpServletRequest request, HttpServletResponse response) {
        logger.info("wechatPayNotify ----- being");
        try {
            ResultBean resultBean = payNotifyOprateLocalService.wechatNotifyOprate(request.getInputStream());
            if(resultBean.getCode() == ResultCode.UNSUCCESS.get_code()) { //解析参数失败需要重发
                wechatSendReturn(response, GlobalConstants.WECHAT_PAY_NOTIFY_RETURN_FAIL,"解析失败");
            } else  { //解析成功。不需重发
                wechatSendReturn(response, GlobalConstants.WECHAT_PAY_NOTIFY_RETURN_SUCCESS,"OK");
            }
            logger.info("wechatPayNotify --------- code:"+ resultBean.getCode() + "; msg:"+resultBean.getMsg());
        } catch (Exception e) {
            logger.error("wechatPayNotify ---------"+e.getMessage());
        }
        logger.info("wechatPayNotify ----- end");
        wechatSendReturn(response, GlobalConstants.WECHAT_PAY_NOTIFY_RETURN_FAIL,"程序异常");
    }

    /**
     * 支付宝app支付回调通知
     * @param request
     * @param response
     */
    @RequestMapping("/alipayAppNotify")
    public void alipayAppNotify(HttpServletRequest request, HttpServletResponse response) {
        logger.info("alipayAppNotify -------进入");
        boolean isSuccess = false;
        try {
            ResultBean resultBean = payNotifyOprateLocalService.alipayAppNotifyOprate(request);

            logger.info("alipayAppNotify -------结束:"+ JSON.toJSONString(resultBean));
        }catch (Exception e) {
            logger.error(e.getMessage());
        }
        aliPaySendReturn(response,isSuccess);
    }

    /**
     * 支付宝及时支付回调通知
     * @param request
     * @param response
     */
    @RequestMapping("/alipaySacnCodeNotify")
    public void alipaySacnCodeNotify(HttpServletRequest request, HttpServletResponse response) {
        boolean isSuccess = false;
        try {
            ResultBean resultBean = payNotifyOprateLocalService.alipaySacnCodeNotifyOprate(request);
            if(resultBean.getCode() == ResultCode.UNSUCCESS.get_code()) { //解析参数失败需要重发
                isSuccess = true;
            } else  { //解析成功。不需重发
                isSuccess = false;
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
            isSuccess = false;
        }
        aliPaySendReturn(response,isSuccess);
    }

    /**
     * 支付宝手机网站支付回调通知
     * @param request
     * @param response
     */
    @RequestMapping("/alipayWapNotify")
    public void alipayWapNotify(HttpServletRequest request, HttpServletResponse response) {
        logger.info("PayNotifyController----alipayWapNotify---begin");
        boolean isSuccess = false;
        try {
            ResultBean resultBean = payNotifyOprateLocalService.alipayWapNotifyOprate(request);
            logger.info("PayNotifyController----alipayWapNotify---res:"+ JSON.toJSONString(resultBean));
            if(resultBean.getCode() == ResultCode.UNSUCCESS.get_code()) { //解析参数失败需要重发
                isSuccess = true;
            } else  { //解析成功。不需重发
                isSuccess = false;
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
            isSuccess = false;
        }
        logger.info("PayNotifyController----alipayWapNotify---end");
        aliPaySendReturn(response,isSuccess);
    }

    /**
     * 微信返回xml格式数据
     * @param response
     * @param returnCode
     * @param returnMsg
     * @throws IOException
     */
    private void wechatSendReturn(HttpServletResponse response, String returnCode, String returnMsg) {
        try {
            StringBuilder resXml = new StringBuilder();
            resXml.append("<xml><return_code><![CDATA[")
                    .append(returnCode)
                    .append("]]></return_code><return_msg><![CDATA[")
                    .append(returnMsg)
                    .append("]]></return_msg></xml>");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/xml; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(resXml.toString());
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 支付宝支付回调通知响应
     * @param response
     * @param isSuccess
     */
    private void aliPaySendReturn(HttpServletResponse response, boolean isSuccess) {
        try {
            String retStr = "success";
            if(!isSuccess) {
                retStr = "fail";
            }
            PrintWriter out = response.getWriter();
            out.write(retStr);
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
